package jehc.cloud.gateway.route.client.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import jehc.cloud.gateway.BaseResult;
import jehc.cloud.gateway.route.client.GatewayNettyClient;
import jehc.cloud.gateway.route.client.GatewayNettyClientUtil;
import jehc.cloud.gateway.route.client.vo.RequestInfo;
import jehc.cloud.gateway.route.service.DynamicRouteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @Desc 客户端处理Handler
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@Slf4j
@Component
public class GatewayNettyClientHandler extends ChannelInboundHandlerAdapter{

    private ApplicationEventPublisher applicationEventPublisher;

    private GatewayNettyClient gatewayNettyClient;

    private String clientId;//客户端id（每个服务对应一个客户端唯一id）

    private String clientGroupId;//组Id（可以存多个服务共享一个组Id）

    DynamicRouteService dynamicRouteService = new DynamicRouteService();

    private static GatewayNettyClientHandler gatewayNettyClientHandler;


    @PostConstruct
    public void init() {
        gatewayNettyClientHandler = this;
    }

    public GatewayNettyClientHandler(){

    }

    public GatewayNettyClientHandler(GatewayNettyClient gatewayNettyClient, String clientGroupId, String clientId){
        this.gatewayNettyClient = gatewayNettyClient;
        this.clientGroupId = clientGroupId;
        this.clientId = clientId;
    }

    public GatewayNettyClientHandler(GatewayNettyClient gatewayNettyClient, String clientGroupId, String clientId,ApplicationEventPublisher applicationEventPublisher){
        this.gatewayNettyClient = gatewayNettyClient;
        this.clientGroupId = clientGroupId;
        this.clientId = clientId;
        this.applicationEventPublisher = applicationEventPublisher;
    }


    /**
     * 连接服务器成功 发送握手信息
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        RequestInfo requestInfo = new RequestInfo();
        requestInfo.setClientGroupId(clientGroupId);
        requestInfo.setClientId(clientId);
        requestInfo.setShakeHands(true);
        requestInfo.setMessage("连接网关路由服务端成功");
        GatewayNettyClientUtil nettyClientUtil = new GatewayNettyClientUtil();
        nettyClientUtil.sendMessage(ctx.channel(),requestInfo);
        log.info("连接网关路由服务端成功 .....");
    }

    /**
     * 接收服务端信息
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if(null == msg){
            return;
        }
        RequestInfo requestInfo = com.alibaba.fastjson.JSONObject.parseObject(msg.toString(), RequestInfo.class);
        log.info("网关路由 Received message from server: {}", requestInfo.getMessage());
        BaseResult baseResult = dynamicRouteService.doRequestInfo(requestInfo,applicationEventPublisher);
        log.info("更新动态路由结果：{}",baseResult.getSuccess());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    /**
     * 服务端挂了 调用重连机制
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        gatewayNettyClient.start();
        super.channelInactive(ctx);
    }
}
